export class DB {
  constructor(name) {
    console.log(name);
    this.name = name;
  }
  isNull() {
    return this._get().length == 0;
  }
  _get() {
    const str = localStorage.getItem(this.name);
    if (str) {
      return JSON.parse(str);
    } else {
      return [];
    }
  }
  _set(list) {
    const str = JSON.stringify(list);
    localStorage.setItem(this.name, str);
  }
  getList(keyword = "") {
    const list = this._get();
    return list.filter((item) => {
      return item.name.includes(keyword);
    });
  }
  delete(id) {
    const list = this._get();
    const index = list.findIndex((i) => i.id == id);
    list.splice(index, 1);
    this._set(list);
  }
  add(obj) {
    const list = this._get();
    let big = 0;
    list.forEach((item) => {
      console.log(Math.max(big, item.id));
      big = Math.max(big, item.id);
    });
    obj.id = big + 1;
    console.log(obj);
    list.unshift(obj);
    this._set(list);
  }
  update(obj) {
    const list = this._get();
    const index = list.findIndex((i) => i.id == obj.id);
    list[index] = { ...list[index], ...obj };
    this._set(list);
  }
  init(list) {
    this._set(list);
  }
}
